package com.sxm.yiwei.activitis;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.tools.BaseIntents;
import com.sxm.yiwei.tools.BookPayActivity;
import com.sxm.yiwei.tools.CropPictures;
import com.sxm.yiwei.tools.IsLogin;
import com.sxm.yiwei.tools.SendBookTime;
import com.sxm.yiwei.utils.InternetAddressUtis;
import com.sxm.yiwei.utils.SPopupWindow;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class HelpActivity extends BaseActivity implements View.OnClickListener{

    private ImageView helpback;
    private LinearLayout helplayout;

    private static final int PHOTO_PICKED_WITH_DATA = 3021;
    private static final int PHOTO_TEXT = 3022;
    private static final int CAMERA_WITH_DATA = 3023;
    private ImageView helpimg1,helpimg2,helpimg3;
    private Bitmap photo;
    private String path1;
    private int currentIndex;
    private List<String> imglist = new ArrayList();

    private EditText inneed;
    private RelativeLayout chooeslink;
    private TextView linktext;
    private static final int ADDRESSTWO = 1002;
    private String linkId = null;
    private SPopupWindow takePhotoPopWin;
    private WindowManager.LayoutParams params;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private Button helpSend;
    private String need;
    private String link;
    private EditText inprice;
    private String price;
    private String time;

    private AlertDialog dialog;
    private TextView helpx;
    private CheckBox helpbox;
    private ImageView imgbt;
    private LinearLayout imgline;
    private RelativeLayout helpafter;
    private TextView timetext;
    private ImageView helpintro;
    private BaseIntents baseIntents;
    private ImageView backmain;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_help);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid","1");
        userId = sharedPreferences.getString("userId", "0");
        token = sharedPreferences.getString("token", "2");
        // 实例化控件
        initHelpView();
        baseIntents = new BaseIntents();
        helpbox.setChecked(true);

        long l = System.currentTimeMillis();
        SendBookTime sendBookTime = new SendBookTime();
        String result = sendBookTime.getTime(l);
        String[] split = result.split("/");
        timetext.setText(split[1]);
        time = split[0];
    }
    private void initHelpView() {
        backmain = (ImageView) findViewById(R.id.help_backmain);

        helpintro = (ImageView) findViewById(R.id.help_selectintro);
        helpback = (ImageView) findViewById(R.id.help_back);
        helpafter = (RelativeLayout) findViewById(R.id.help_after);
        helplayout = (LinearLayout) findViewById(R.id.help_imgs);
        helpimg1 = (ImageView) findViewById(R.id.help_img1);
        helpimg2 = (ImageView) findViewById(R.id.help_img2);
        helpimg3 = (ImageView) findViewById(R.id.help_img3);
        imgbt = (ImageView) findViewById(R.id.help_imgbt);
        imgline = (LinearLayout) findViewById(R.id.help_imgline);
        inneed = (EditText) findViewById(R.id.help_inneed);
        chooeslink = (RelativeLayout) findViewById(R.id.help_chooseLink);
        linktext = (TextView) findViewById(R.id.help_linktext);
        helpSend = (Button) findViewById(R.id.help_send);
        inprice = (EditText) findViewById(R.id.help_inprice);
        helpx = (TextView) findViewById(R.id.help_x);
        helpbox = (CheckBox) findViewById(R.id.help_box);
        timetext = (TextView) findViewById(R.id.help_timetext);


        // 设置点击事件
        helpafter.setOnClickListener(this);
        helpback.setOnClickListener(this);
        helpimg1.setOnClickListener(this);
        helpimg2.setOnClickListener(this);
        helpimg3.setOnClickListener(this);
        chooeslink.setOnClickListener(this);
        helpSend.setOnClickListener(this);
        helpx.setOnClickListener(this);
        imgbt.setOnClickListener(this);
        helpintro.setOnClickListener(this);
        backmain.setOnClickListener(this);
    }

        // 点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.help_backmain:
                startActivity(new Intent(HelpActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
            case R.id.help_selectintro:
                Intent intent = new Intent(HelpActivity.this,HotSendSelectTypeActivity.class);
                intent.putExtra("from","2");
                startActivityForResult(intent,101);
                break;

            case R.id.help_imgbt:
                helplayout.setVisibility(View.VISIBLE);
                imgline.setVisibility(View.VISIBLE);
                break;
            case R.id.help_back:
                finish();
                break;
            case R.id.help_x:
                Intent i = new Intent(HelpActivity.this,WEBXActivity.class);
                i.putExtra("from","hot");
                i.putExtra("url", InternetAddressUtis.XNOSEND);
                startActivity(i);
                break;
            case R.id.help_chooseLink:
                if (IsLogin.isLogin()){
                    Intent intentcall = new Intent(HelpActivity.this,AddCloseActivity.class);
                    intentcall.putExtra("from","2");
                    startActivityForResult(intentcall,ADDRESSTWO);
                }else {

                }
                break;
            case R.id.help_send:
                if (IsLogin.isLogin()) {
                    getInData();
                    if (!helpbox.isChecked()) {
                        Toast.makeText(this, "请阅读同意相关协议", Toast.LENGTH_SHORT).show();
                    } else {
                        if (need.equals("")) {
                            Toast.makeText(this, "请输入需求", Toast.LENGTH_SHORT).show();
                        } else {
                            if (linkId == null) {
                                Toast.makeText(this, "请选择收件人", Toast.LENGTH_SHORT).show();
                            } else {
                                if (price.equals("")) {
                                    Toast.makeText(this, "请输入酬金", Toast.LENGTH_SHORT).show();
                                } else {
                                    Double dprice = Double.valueOf(price);
                                    if (dprice >= 10.0) {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(HelpActivity.this, R.style.NoBackGroundDialog);
                                        View view = LayoutInflater.from(this).inflate(R.layout.progress_dialog, null);
                                        ProgressBar diapro = (ProgressBar) view.findViewById(R.id.pro_dia);
                                        builder.setView(view);
                                        dialog = builder.create();
                                        dialog.show();
                                        sendHelp();
                                    } else {
                                        Toast.makeText(this, "价格不能低于10.00元", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        }
                    }
                }else {}
                break;

            case R.id.help_after:
                takePhotoPopWin = new SPopupWindow(this,this);
//        设置Popupwindow显示位置（从底部弹出）
                takePhotoPopWin.showAtLocation(findViewById(R.id.help_view), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
                params = getWindow().getAttributes();
                //当弹出Popupwindow时，背景变半透明
                params.alpha=0.7f;
                getWindow().setAttributes(params);
                //设置Popupwindow关闭监听，当Popupwindow关闭，背景恢复1f
                takePhotoPopWin.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        params = getWindow().getAttributes();
                        params.alpha=1f;
                        getWindow().setAttributes(params);
                    }
                });
                takePhotoPopWin.setOnCilckButton(new SPopupWindow.OnClickButton() {
                    @Override
                    public void OnClickButton(String s,String stime) {
                        timetext.setText(s);
                        time=stime;
                    }
                });

                break;
            case R.id.help_img1:
                currentIndex=0;
                doPickPhotoAction();
                break;
            case R.id.help_img2:
                currentIndex=1;
                doPickPhotoAction();
                break;
            case R.id.help_img3:
                currentIndex=2;
                doPickPhotoAction();
                break;
        }
    }
        // 发送订单 成功后钱包支付
    private void sendHelp() {
        getInData();

        RequestParams p = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.SENDHELP);
        p.addHeader("Content-Type","multipart/form-data");
        p.addHeader("token",token);
        p.addHeader("appId",appId);
        p.addHeader("userId",userId);
        p.addBodyParameter("consignorId",linkId);
        p.addBodyParameter("total_amount",price);
        p.addBodyParameter("appointTime",time);
        p.addBodyParameter("intro",need);
        for (int i = 0; i < imglist.size(); i++) {
            p.addBodyParameter("order",new File(imglist.get(i)));
        }
        p.setMultipart(true);

        x.http().post(p, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                dialog.dismiss();
                JSONObject object = JSON.parseObject(result);
                String data = object.getString("data");
                JSONObject object1 = JSON.parseObject(data);
                String orderId = object1.getString("orderId");
                getInData();
                Intent in = new Intent(HelpActivity.this,BookPayActivity.class);
                in.putExtra("from","help");
                in.putExtra("amount",String.valueOf(price));
                in.putExtra("id",orderId);
                in.putExtra("alipay",InternetAddressUtis.SENDBOOK_ALIPAY);
                in.putExtra("yivipay",InternetAddressUtis.ONE_SENDPAY);
                startActivity(in);
                finish();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getInData() {
        need = String.valueOf(inneed.getText());
        link = String.valueOf(linktext.getText());
        price = String.valueOf(inprice.getText());
    }

    private void doPickPhotoAction() {
        final Context context = this;
        AlertDialog.Builder b1 = new AlertDialog.Builder(context);
        View view = LayoutInflater.from(context).inflate(R.layout.picture_dialog, null);
        b1.setView(view);

        TextView camere = (TextView) view.findViewById(R.id.picdia_camere);
        TextView pic = (TextView) view.findViewById(R.id.picdia_pic);
        TextView cancel1 = (TextView) view.findViewById(R.id.picdia_cancel);

        final AlertDialog dialog1 = b1.create();
        Window window = dialog1.getWindow();
        camere.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String status= Environment.getExternalStorageState();
                if(status.equals(Environment.MEDIA_MOUNTED)){//判断是否有SD卡
                    // index=0;
                    baseIntents.doTakePhoto();// 用户点击了从照相机获取
                    dialog1.dismiss();
                }
                else{
                    Toast.makeText(context, "没有SD卡", Toast.LENGTH_SHORT).show();
                }
            }
        });
        pic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                baseIntents.doPickPhotoFromGallery();// 从相册中去获取
                dialog1.dismiss();
            }
        });
        cancel1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog1.dismiss();
            }
        });
        dialog1.show();
        window.setGravity(Gravity.BOTTOM);

    }


    // 因为调用了Camera和Gally所以要判断他们各自的返回情况,他们启动时是这样的startActivityForResult
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
                //final Bitmap photo = data.getParcelableExtra("data");
                Bitmap photo = data.getParcelableExtra("data");
                String s = CropPictures.saveBitmapFile(photo, new BaseIntents().getPhotoFileName());
                imglist.add(s);
                switch (imglist.size()){
                    case 0:

                        break;
                    case 1:
                        helpimg2.setVisibility(View.VISIBLE);
                        break;
                    case 2:
                        helpimg3.setVisibility(View.VISIBLE);
                        break;
                }

                if (currentIndex==0){
                    helpimg1.setImageBitmap(photo);
                }else if (currentIndex==1){
                    helpimg2.setImageBitmap(photo);
                }else if (currentIndex==2){
                    helpimg3.setImageBitmap(photo);
                }else if (currentIndex==3){

                }
            }

            break;
            case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
                baseIntents.doCropPhoto(baseIntents.mCurrentPhotoFile);
                break;
            }

            case PHOTO_TEXT:
                Uri data1 = data.getData();
                if (!TextUtils.isEmpty(data1.getAuthority())){
                    ContentResolver resolver = getContentResolver();
                    try {
                        photo = MediaStore.Images.Media.getBitmap(resolver, data1);
                        String[] proj = {MediaStore.Images.Media.DATA};
                        Cursor cursor = managedQuery(data1, proj, null, null, null);
                        if (cursor==null){
                            Toast.makeText(this, "没有找到图片", Toast.LENGTH_SHORT).show();
                        }else {
                            cursor.moveToFirst();
                            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                            //图片路径
                            path1 = cursor.getString(column_index);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    path1 = data1.getPath();
                }
                File file = new File(path1);
                baseIntents.doCropPhoto(file);
                break;
            case ADDRESSTWO:
                // 获取联系人 返回的数据
                Bundle ab = data.getExtras();
                String address1 = String.valueOf(ab.get("address"));
                String name1 = String.valueOf(ab.get("name"));
                linkId = String.valueOf(ab.get("id"));
                linktext.setText(name1+" "+address1);
                break;
            case 101:
                Bundle extras = data.getExtras();
                String item = extras.getString("item");
                inneed.setText(item);
                break;
        }

    }

}
